﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Security.Principal;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using Flash.Internal;

namespace Flash
{
    public abstract class LoadHandler : LoadVarsHandler
    {
        #region Constructors

        public LoadHandler()
            : base()
        {
        }

        public LoadHandler(bool returnError)
            : base(returnError)
        {
        }

        public LoadHandler(bool returnError, string errorFieldName)
            : base(returnError, errorFieldName)
        {
        }

        #endregion

        protected override void ProcessRequest()
        {
            var properties = ReflectionHelper.GetFlashVariableProperties(this.GetType())
                .Where(x => ReflectionHelper.CheckMemberAccessForPrincipal(User, x)).ToArray();

            if (properties.Length == 0)
            {
                throw new AccessDeniedException();
            }

            foreach (var prop in properties)
            {
                object value = prop.GetValue(this, null);
                string str = value == null ? null : value.ToString();

                FlashResponse.AddParameter(prop.GetAttributeInfo<FlashVariableAttribute>().MapToVariable ?? prop.Name, str);
            }
        }
    }
}